<?php


namespace App\Services;


class DouyinService
{
    /**
     * 微信
     * @param $message
     * @param array $request
     * @param array $response
     */
    public static function requestLog($message,$request=[],$response=[]){
        $content = [
            'request'=>is_object($request) ? object_array($request) : $request,
            'response'=>is_object($response) ? object_array($response) : $response,
        ];
        \Illuminate\Support\Facades\Log::debug($message,$content);
    }
    public static function addLog($message,$request=[],$response=[]){
        $content = [
            'request'=>is_object($request) ? object_array($request) : $request,
            'response'=>is_object($response) ? object_array($response) : $response,
        ];
        \Illuminate\Support\Facades\Log::debug($message,$content);
    }


    /**
     * 获取accessToken
     * @return array
     */
    public static function getAccessToken(){
        $data =  [];
        $url = config('douyin.apiUrl')."/cgi-bin/token";
        $param = [
            'appid'=>config('douyin.appId'),
            'secret'=>config('douyin.appSecret'),
            'grant_type'=>'client_credential',
        ];
        $result = http_get($url,$param);
        $result = json_decode($result,true);
        if (isset($result['errcode'])) {
            $flag =  false;
        }else{
            $flag =  true;
            $data = $result;
        }
        return ['status'=>$flag, 'message'=>$flag ? '成功' : '失败','data'=>$data];
    }

    /**
     * 小程序授权
     * @param $code
     * @return array
     */
    public static function authToken($code,$anonymous_code){
        $data =  [];
        $url = config('douyin.apiUrl')."/api/apps/v2/jscode2session";
        $param = [
            'appid'=>config('douyin.appId'),
            'secret'=>config('douyin.appSecret'),
            'anonymous_code'=>$anonymous_code,
            'code'=>$code,
        ];

        $result = http_post($url,json_encode($param));
        $result = json_decode($result,true);
        self::requestLog('小程序授权登录',['code'=>$code],$result);
        if (isset($result['errCode'])) {
            $flag =  false;
        }else{
            $flag =  true;
            $data = $result;
        }
        return ['status'=>$flag, 'message'=>$flag ? '成功' : '失败','data'=>$data];
    }

    /**
     * 获取手机号
     * @param $code
     * @return array
     */
    public static function getMobile($code){
        $accessToken = self::getAccessToken();
        if(!$accessToken['status']){
            $flag =  false;
        }else{
            $data =  [];
            $url = config('douyin.apiUrl')."/wxa/business/getuserphonenumber?access_token=".$accessToken['data']['access_token'];
            $param = [
                'code'=>$code,
            ];
            $result = http_post($url,json_encode($param),['Content-type: application/json;charset=UTF-8']);
            $result = json_decode($result,true);
            self::requestLog('小程序获取手机号',['code'=>$code],$result);
            //成功
            if (isset($result['errcode']) && $result['errcode'] == 0) {
                $flag =  true;
                $data = $result;
            }else{
                $flag =  false;
            }
        }
        return ['status'=>$flag, 'message'=>$flag ? '成功' : '失败','data'=>$data];
    }


    public function DouyinPay($order){

        $outOrderNo = $order['trade_no'];//开发者侧的订单号
        $totalAmount = $order['total_fee'];//支付价格; 接口中参数支付金额单位为[分]
        $subject = "订单号：".$order['trade_no']; //商品描述也就是标题
        $body = $order['goods_title'];
        $validTimestamp = 60 * 60;//订单过期时间(秒);
        $notifyUrl = "https://***/notify"; //这里可以忽略，走字节跳动小程序 -支付 -担保配置-设置回调地址
        //创建订单
        $response = $this->createOrder($outOrderNo, $totalAmount, $subject, $body, $validTimestamp, $notifyUrl);

       return $response;
    }
    /**
     *	创建订单
     */
    public function CreateOrder($outOrderNo, $totalAmount, $subject, $body, $validTimestamp, $notifyUrl)
    {
        $params = [
            'app_id'       => config('douyin.appId'),//小程序appid
            'out_order_no' => $outOrderNo,
            'total_amount' => $totalAmount * 100,
            'subject'      => $subject,
            'body'         => $body,
            'valid_time'   => $validTimestamp,
            'notify_url'   => $notifyUrl,

        ];

        $params = array_filter($params);
        $params['sign'] = $this->sign($params);

        $result = http_post('https://developer.toutiao.com/api/apps/ecpay/v1/create_order',json_encode($params),['Content-type: application/json;charset=UTF-8']);

        return $result;
    }
    public function sign($map) {
        $rList = [];
        foreach($map as $k =>$v) {
            if ($k == "other_settle_params" || $k == "app_id" || $k == "sign" || $k == "thirdparty_id") continue;

            $value = trim(strval($v));
            if (is_array($v)) {
              $value = arrayToStr($v);
            }

            $len = strlen($value);
            if ($len > 1 && substr($value, 0,1)=="\"" && substr($value, $len-1)=="\"")
                $value = substr($value,1, $len-1);
            $value = trim($value);
            if ($value == "" || $value == "null")
                continue;
            $rList[] = $value;
        }
        $rList[] = "TIAbXVABKvbXoLgB5SQwjG7J4SWSw8Xw9ee6F4LB";
        sort($rList, SORT_STRING);
        return md5(implode('&', $rList));
    }


        public function arrayToStr($map) {
          $isMap = isArrMap($map);

            $result = "";
            if ($isMap){
              $result = "map[";
            }

            $keyArr = array_keys($map);
            if ($isMap) {
                sort($keyArr);
            }

            $paramsArr = array();
            foreach($keyArr as  $k) {
              $v = $map[$k];
              if ($isMap) {
                if (is_array($v)) {
                  $paramsArr[] = sprintf("%s:%s", $k, arrayToStr($v));
                } else  {
                  $paramsArr[] = sprintf("%s:%s", $k, trim(strval($v)));
                }
              } else {
                if (is_array($v)) {
                  $paramsArr[] = arrayToStr($v);
                } else  {
                  $paramsArr[] = trim(strval($v));
                }
              }
            }

            $result = sprintf("%s%s", $result, join(" ", $paramsArr));
            if (!$isMap) {
              $result = sprintf("[%s]", $result);
            } else {
              $result = sprintf("%s]", $result);
            }

            return $result;
        }

        public function isArrMap($map) {
            foreach($map as $k =>$v) {
              if (is_string($k)){
                  return true;
              }
            }

            return false;
        }


}
